package com.example.ssmlab1.controller;
import com.mysql.jdbc.DatabaseMetaData;
import org.apache.commons.dbcp.BasicDataSource;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

public class DB {
    //数据库连接池
    private static BasicDataSource basicDataSource = new BasicDataSource();

    // 静态块
    static {
        basicDataSource.setDriverClassName("com.mysql.jdbc.Driver");
        basicDataSource.setUrl("jdbc:mysql:///?useSSL=false");
        basicDataSource.setUsername("root");
        basicDataSource.setPassword("123456");
    }

    public static Connection getConnection() {
        try {
            return basicDataSource.getConnection();
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }

    //为了简介代码 方便调用close
    public static void close(ResultSet resultSet, PreparedStatement preparedStatement, Connection connection) {
        // 返回值
        if (resultSet != null) {
            try {
                resultSet.close();
            } catch (SQLException e) {
                throw new RuntimeException(e);
            }
        }
        // 预编译处理
        if (preparedStatement != null) {
            try {
                preparedStatement.close();
            } catch (SQLException e) {
                throw new RuntimeException(e);
            }
        }
        // 数据库连接
        if (connection != null) {
            try {
                connection.close();
            } catch (SQLException e) {
                throw new RuntimeException(e);
            }
        }
    }
}
